import React from 'react'
import {
  Cascader,
  App,
  Input,
  Tree,
  Modal,
  Space,
  Button,
  Image,
  Alert,
  Drawer,
  Tag,
  Popconfirm,
  Form,
  Radio
} from 'antd'
import { ProTable } from '@ant-design/pro-components'
import { LinkOutlined, DownOutlined, CloseOutlined } from '@ant-design/icons'
import { useModel } from '@umijs/max'
import { useState, useRef } from 'react'
import styles from './LinkFormat.less'

const cascaderOptions = [
  {
    value: 'product',
    label: '选择商品'
  },
  {
    value: 'category',
    label: '商品分类'
  },
  {
    value: 'custom',
    label: '自定义链接'
  }
]

function LinkFormat(props) {
  const { message } = App.useApp()
  const { value, onChange } = props
  const { GetCategorySelections, GetPlatformGoodsList, GetShopSelections } = useModel('Goods')
  const { currentTab } = useModel('ShopDecoration')

  // 分类弹窗
  const [editCategoryModal, setEditCategoryModal] = useState(false) // 选择分类弹窗
  const [categoryList, setCategoryList] = useState([]) // 分类列表
  const [categoryCheckedList, setCategoryCheckedList] = useState([]) // 选中的分类列表
  const [defaultExpandList, setDefaultExpandList] = useState([]) // 默认展开的分类列表
  const [isConfirm, setIsConfirm] = useState(true) // 是否能够确认选择分类

  let tabObj = {
    'mp-alipay': 1,
    'mp-weixin': 2,
    app: 3,
    h5: 4
  }

  //  获取分类列表
  const getCategoryList = async e => {
    let params = e ? { cate_name: e } : {}
    params.plt = tabObj[currentTab?.label]
    const res = await GetCategorySelections(params)
    let list = []
    setCategoryList(
      res.map(i => {
        if (i.children && i.children.length) list.push(i.id)
        return {
          title: i.cate_name,
          key: i.id,
          disableCheckbox: true,
          children: i.children
            ? i.children.map(ch => ({
                title: ch.cate_name,
                key: ch.id,
                isChild: true
              }))
            : []
        }
      })
    )
    setDefaultExpandList(list)
    if (!e) {
      return Promise.resolve()
    }
  }

  // 关闭选择分类弹窗
  const closeEditCategoryModal = () => {
    setEditCategoryModal(false)
  }

  // 提交选择分类
  const handleConfirmEditCate = async () => {
    if (isConfirm) return
    if (categoryCheckedList.length) {
      onChange(categoryCheckedList)
      setCategoryCheckedList([])
      closeEditCategoryModal()
    } else {
      message.warning('请至少选择一个分类')
    }
    setIsConfirm(true)
  }

  // 选择类目处理
  const handleSelectCate = (selected, e) => {
    const { isChild } = e.node
    if (!isChild) {
      message.warning('请选择子分类')
      selected.pop()
      return
    }
    const list = selected.map(item => {
      return {
        id: item,
        name: e.node.title,
        link: `/pages/category/categoryDetails/categoryDetails?id=${item}`,
        type: 'category',
        display_category_list: false
      }
    })

    setIsConfirm(false)
    setCategoryCheckedList(list)
  }

  // 选择商品抽屉
  const [goodsDrawer, setGoodsDrawer] = useState(false) // 选择商品抽屉
  const [drawerSelectGoods, setDrawerSelectGoods] = useState([]) // 选择的商品
  const [addGoodsPageSize, setAddGoodsPageSize] = useState(5) //  每页数量
  const [shopList, setShopList] = useState([]) // 店铺列表
  const selectGoodsTableRef = useRef() // 选择商品表格ref

  // 开关商品抽屉
  const triggerGoodsDrawer = () => {
    setGoodsDrawer(!goodsDrawer)
  }

  // 处理商品抽屉选择商品
  const handleDisplay = async () => {
    if (!drawerSelectGoods.length) {
      message.warning('请最少选择一个商品')
      return
    }
    onChange(drawerSelectGoods)
    setDrawerSelectGoods([])
    triggerGoodsDrawer()
  }

  // 跳转商品页
  const goProduct = (type, id, merchant_id) => {
    let url = `/product?type=${type}&id=${id}&merchant_id=${merchant_id}`
    window.open(url)
  }

  //  获取店铺列表
  const getShopList = async () => {
    const res = await GetShopSelections()
    if (res) setShopList(res.map(i => [i.id, i.shop_name]))
  }

  // 选择分类 / 商品 处理
  const handleCascaderChange = async (e, type) => {
    let event
    if (type === 'open') {
      event = e[0]
    } else if (type === 'edit') {
      event = e[0].type
    }

    if (event === 'category') {
      await getCategoryList()
      if (value && value.length) {
        let valueList = value.map(i => i.id)
        setCategoryCheckedList(valueList)
      }
      setEditCategoryModal(true)
    } else if (event === 'product') {
      triggerGoodsDrawer()
      if (value && value.length) {
        setDrawerSelectGoods(value)
      }
    } else if (event === 'custom') {
      setCustomModal(true)
      if (value && value.length) {
        customForm.setFieldsValue(value[0])
      }
    }
  }

  // 更新商品列表
  const handleUpdate = () => {
    setDrawerSelectGoods([])
    setCategoryCheckedList([])
    onChange([])
  }

  // 修改商品/分类
  const handleEdit = () => {
    handleCascaderChange(value, 'edit')
  }

  const selectGoodsColumns = [
    {
      title: '商品名称',
      dataIndex: 'goods_name',
      width: 200,
      render: (text, record) => (
        <Space>
          <Image width={48} src={record.goods_cover_url} />
          <a onClick={() => goProduct(3, record.id, record.merchant_id)}>{text}</a>
        </Space>
      )
    },
    {
      title: '商品ID',
      dataIndex: 'id',
      width: 60,
      hideInTable: true
    },
    {
      title: '买断价',
      dataIndex: 'buyout_price_range',
      hideInSearch: true,
      width: 140
    },
    {
      title: '租赁信息',
      dataIndex: 'rent_meal_info',
      hideInSearch: true,
      width: 300,
      render: (text, record) => {
        const { use_scope } = record
        if (use_scope && use_scope.includes('rent')) {
          const { deposit, lease_terms, per_rent_range, periods } = text
          return (
            <>
              <div>
                押金：{deposit[0]}~{deposit[1]}
              </div>
              <div>
                租期：{periods[0]}~{periods[1]}
              </div>
              <div>
                期数：{lease_terms[0]}~{lease_terms[1]}
              </div>
              <div>
                每期租金：{per_rent_range[0]}~{per_rent_range[1]}
              </div>
            </>
          )
        } else {
          return '/'
        }
      }
    },
    {
      title: '买卖信息',
      dataIndex: 'buy_meal_info',
      hideInSearch: true,
      width: 300,
      render: (text, record) => {
        const { use_scope } = record
        if (use_scope && use_scope.includes('buy')) {
          const { first_pay_range, lease_terms, per_rent_range, periods } = text
          return (
            <>
              <div>
                首付款：{first_pay_range[0]}~{first_pay_range[1]}
              </div>
              <div>
                尾期：{lease_terms[0]}~{lease_terms[1]}
              </div>
              <div>
                期数：{periods[0]}~{periods[1]}
              </div>
              <div>
                每期尾款：{per_rent_range[0]}~{per_rent_range[1]}
              </div>
            </>
          )
        } else {
          return '/'
        }
      }
    },
    {
      title: '物流配送',
      dataIndex: 'delivery_type_names',
      width: 120,
      hideInSearch: true,
      render: text => (
        <>
          {text.map(i => (
            <div key={i} className={styles.delivery_name}>
              {i}
            </div>
          ))}
        </>
      )
    },
    {
      title: '归属店铺',
      dataIndex: 'shop_name',
      valueType: 'select',
      valueEnum: new Map(shopList),
      width: 120
    },
    {
      title: '提交时间',
      dataIndex: 'create_time',
      hideInSearch: true,
      width: 220
    },
    {
      title: '操作',
      key: 'option',
      width: 80,
      valueType: 'option',
      fixed: 'right',
      render: (_, row, index, action) => {
        return (
          <a
            key='check'
            onClick={() => {
              goProduct(3, row.id, row.merchant_id)
            }}
          >
            详情
          </a>
        )
      }
    }
  ]

  // 自定义链接
  const [customModal, setCustomModal] = useState(false) // 自定义链接弹窗
  const [customForm] = Form.useForm()

  // 自定义链接提交
  const handleConfirmCustomLink = async () => {
    await customForm.validateFields()
    const values = customForm.getFieldsValue()

    let list = [
      {
        ...values,
        name: values.name,
        id: values.link,
        link: values.link,
        linkType: values.linkType,
        type: 'custom',
        display_category_list: false
      }
    ]
    onChange(list)
    setCustomModal(false)
  }

  let cancelRowKeys = [] // 取消选择的项目

  // 格式化商品列表
  const formatList = list => {
    return list.map(item => {
      const commonProps = {
        name: item.goods_name,
        id: item.id,
        type: 'product'
      }

      if (list.length === 1) {
        return {
          ...commonProps,
          link: `/pages/index/goodsDetails/goodsDetails?id=${item.id}`,
          display_category_list: false
        }
      } else {
        return {
          ...commonProps,
          link: `/pages/category/categoryList/categoryList`,
          display_category_list: true
        }
      }
    })
  }

  return (
    <>
      {value && value.length ? (
        <>
          <Popconfirm title='确认删除吗?' onConfirm={() => handleUpdate()} okText='确认' cancelText='取消'>
            <Tag color='processing'>
              已选择(
              {value[0].type === 'category' && <span>分类-{value[0].name}</span>}
              {value[0].type === 'product' && <span>{value.length}个商品</span>}
              {value[0].type === 'custom' && <span>自定义链接-{value[0].name}</span>}
              )
              <CloseOutlined />
            </Tag>
          </Popconfirm>
          <span style={{ color: '#4676FB', cursor: 'pointer' }} onClick={handleEdit}>
            <span>修改</span>
            <DownOutlined />
          </span>
        </>
      ) : (
        <Cascader options={cascaderOptions} onChange={e => handleCascaderChange(e, 'open')}>
          <a>
            <LinkOutlined />
            <span style={{ margin: '0 3px' }}>选择跳转到的页面</span>
            <DownOutlined />
          </a>
        </Cascader>
      )}

      {/*选择分类弹窗*/}
      <Modal
        title={'选择分类'}
        mask
        open={editCategoryModal}
        onCancel={closeEditCategoryModal}
        bodyStyle={{ padding: '20px 0' }}
        width={640}
        destroyOnClose
        footer={
          <>
            <Button onClick={closeEditCategoryModal}>取消</Button>
            <Button type={'primary'} onClick={handleConfirmEditCate} disabled={isConfirm}>
              提交
            </Button>
          </>
        }
      >
        <Input.Search
          placeholder='搜索分类名称'
          onSearch={e => getCategoryList(e)}
          style={{ width: '100%', marginBottom: 20 }}
        />
        <Tree
          treeData={categoryList}
          onSelect={handleSelectCate}
          expandedKeys={defaultExpandList}
          height={350}
          defaultSelectedKeys={categoryCheckedList}
        />
      </Modal>

      {/*选择商品抽屉*/}
      <Drawer
        title='选择商品'
        placement='right'
        className={styles.goods_drawer_wrapper}
        onClose={triggerGoodsDrawer}
        open={goodsDrawer}
        width={980}
        destroyOnClose
        footer={
          <div className={styles.drawer_footer}>
            <Space>
              <Button disabled={!drawerSelectGoods.length} onClick={triggerGoodsDrawer}>
                取消
              </Button>
              <Button type='primary' disabled={!drawerSelectGoods.length} onClick={handleDisplay}>
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <Alert message='仅可以选择店铺已经上架的商品，选择后将展示在平台小程序商品列表中。' type='info' showIcon />
        <ProTable
          search={{
            defaultCollapsed: false,
            labelWidth: 75,
            span: 6
          }}
          actionRef={selectGoodsTableRef}
          tableAlertOptionRender={() => {
            return false
          }}
          rowSelection={{
            selectedRowKeys: drawerSelectGoods.map(i => i.id),
            onChange: (keys, rows) => {
              let tempList = [...rows, ...drawerSelectGoods.filter(i => !keys.includes(i.id))]
              if (cancelRowKeys.length) {
                setDrawerSelectGoods(formatList(tempList.filter(i => !cancelRowKeys.includes(i.id))))
              } else {
                setDrawerSelectGoods(formatList(tempList))
              }
            },

            onSelect: (record, selected) => {
              if (!selected) {
                cancelRowKeys = [record.id]
              }
            }
          }}
          request={async params => {
            const param = {
              page: params.current,
              page_size: params.pageSize,
              plt: tabObj[currentTab?.label],
              is_display: 1
            }
            const res = await GetPlatformGoodsList(param)
            getShopList()
            setAddGoodsPageSize(params.pageSize)
            // setDrawerSelectGoods([])
            return {
              data: res.data,
              success: true,
              total: res.total
            }
          }}
          pagination={{
            pageSize: addGoodsPageSize
          }}
          options={false}
          rowKey='id'
          scroll={{ x: 'max-content' }}
          columns={selectGoodsColumns}
        />
      </Drawer>

      {/*自定义链接*/}
      <Modal
        title={'自定义链接'}
        mask
        open={customModal}
        onCancel={() => setCustomModal(false)}
        bodyStyle={{ padding: '20px 0' }}
        width={640}
        destroyOnClose
        footer={
          <>
            <Button onClick={() => setCustomModal(false)}>取消</Button>
            <Button type={'primary'} onClick={handleConfirmCustomLink}>
              提交
            </Button>
          </>
        }
      >
        <Form
          name='customForm'
          form={customForm}
          initialValues={{
            linkType: 'alipay'
          }}
        >
          <Form.Item
            label='名称'
            name='name'
            rules={[
              {
                required: true,
                message: '请输入名称'
              }
            ]}
          >
            <Input allowClear placeholder='请输入名称' />
          </Form.Item>
          <Form.Item
            label='链接'
            name='link'
            rules={[
              {
                required: true,
                message: '请输入链接'
              }
            ]}
          >
            <Input allowClear placeholder='请输入链接' />
          </Form.Item>
          <Form.Item
            label='类型'
            name='linkType'
            rules={[
              {
                required: true,
                message: '请选择类型'
              }
            ]}
          >
            <Radio.Group>
              {currentTab?.label === 'mp-alipay' && <Radio value={'alipay'}>支付宝页面</Radio>}
              <Radio value={'applet'}>小程序内部页面</Radio>
              <Radio value={'web'}>外部链接</Radio>
            </Radio.Group>
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}

export default LinkFormat
